package com.hsnn.medstgmini.base.std.dao.impl;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.impl.BaseHibernateDAO;
import com.hsnn.medstgmini.base.dict.model.DicCompType;
import com.hsnn.medstgmini.base.std.dao.StdCompinfoDao;
import com.hsnn.medstgmini.base.std.model.StdCompinfo;
import com.hsnn.medstgmini.base.std.model.StdCompinfoDetailLog;
import com.hsnn.medstgmini.base.std.model.StdCompinfoLog;
import com.hsnn.medstgmini.base.std.model.form.StdProdDrugInfoForm;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.model.Status;
import com.hsnn.medstgmini.util.Pagination;

/**
 * 企业库 实现类DAO
 * 
 * @author hss@njhsnn 2015年6月9日
 */
@Repository
public class StdCompinfoDaoImpl extends BaseHibernateDAO implements
		StdCompinfoDao {
	private static final Logger log = Logger
			.getLogger(StdCompinfoDaoImpl.class);

	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	@Autowired
	private HibernateSqlUtil hibernateSqlUtil;

	/**
	 * 企业库 新增及修改
	 * 
	 * @param stdCompinfo
	 */
	@Override
	public void addAndEdit(StdCompinfo stdCompinfo) {
		Session session = sessionFactory.getCurrentSession();
		String stdCompId = stdCompinfo.getCompId();
		if (StringUtils.isNotBlank(stdCompId)) {
			if(null != stdCompinfo.getStdCompinfoDetail()){
				stdCompinfo.getStdCompinfoDetail().setCompId(stdCompId);
			}
			session.update(stdCompinfo);
			session.flush();
			LogSave(stdCompinfo);
		}
		if (StringUtils.isBlank(stdCompId)) {
			stdCompinfo.setCompId(UUID.randomUUID().toString());
			if(null != stdCompinfo.getStdCompinfoDetail()){
				stdCompinfo.getStdCompinfoDetail().setCompId(
						stdCompinfo.getCompId());
			}
			session.save(stdCompinfo);
			session.flush();
			LogSave(stdCompinfo);
		}
	}
	/**
	 * 企业新增
	 */
	@Override
	public void addForm(StdCompinfo stdCompinfo) {
		Session session = getSession();
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into dic_compinfo(comp_id as compId,comp_code as compCode,comp_name as compName,comp_spel_code as compSpelCode,comp_name_eng as compNameEng,comp_short_name as compShortName,  ")
			.append(" comp_short_spel_code as compShortSpelCode,comp_type as compType,area_id as areaId,comp_reg_id as compRegId,org_code as orgCode,comp_group_id compGroupId,comp_phone as compPhone, ")
			.append(" comp_address as compAddress,comp_classify as compClassify,status as status,upd_datetime as upDatetime,upd_user as updUser,history_code as historyCode,merge_state as mergeState ")
		    .append(" ) values ( ")
		    .append(":compId,:compCode,:compName,:compSpelCode,:compNameEng ,:compShortName ,:compShortSpelCode ,:compType ,:areaId ,:compRegId ,:orgCode ,:compGroupId ,:compPhone ,:compAddress ,:compClassify ,1 ,:upDatetime ,:historyCode ,:mergeState ) ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("compId",stdCompinfo.getCompId());
		query.setString("compCode",stdCompinfo.getCompCode());
		query.setString("compName",stdCompinfo.getCompName());
		query.setString("compSpelCode",stdCompinfo.getCompSpelCode());
		query.setString("compNameEng",stdCompinfo.getCompNameEng());
		query.setString("compShortName",stdCompinfo.getCompShortName());
		query.setString("compShortSpelCode",stdCompinfo.getCompShortSpelCode());
		query.setShort("compType",stdCompinfo.getCompType());
		query.setString("areaId",stdCompinfo.getAreaId());
		query.setString("compRegId",stdCompinfo.getCompRegId());
		query.setString("orgCode",stdCompinfo.getOrgCode());
		query.setString("compGroupId",stdCompinfo.getCompGroupId());
		query.setString("compPhone",stdCompinfo.getCompPhone());
		query.setString("compAddress",stdCompinfo.getCompAddress());
		query.setShort("compClassify",stdCompinfo.getCompClassify());
		query.setTimestamp("upDatetime",stdCompinfo.getUpdDatetime());
		query.setString("historyCode",stdCompinfo.getHistoryCode());
		query.setShort("mergeState",stdCompinfo.getMergeState());
		session.flush();
		writeLog(stdCompinfo);	
	}

	/**
	 * 企业库 信息查询及条件查询
	 * 
	 * @param stdCompinfo
	 * @return
	 */
	public Pagination queryStdCompinfoList(Pagination page,StdCompinfo stdCompinfo) {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"SELECT A.comp_id compId, A.comp_code compCode, A.comp_name compName,A.org_code orgCode, A.comp_spel_code compSpelCode,A.comp_type compType, A.area_id areaId,")
				.append(" A.comp_reg_id compRegId, A.status status, A.upd_datetime updDatetime, B.ar_fullname arFullname, C.comp_reg_name compRegName FROM std_compinfo A LEFT JOIN")
				.append(" dic_area B on A.area_id = B.area_id LEFT JOIN dic_comptype C on C.comp_reg_id = A.comp_reg_id where 1 = 1");
		Map<String, Object> param = new HashMap<String, Object>();
		if (null != stdCompinfo.getCompType()
				&& !"".equals(stdCompinfo.getCompType())) {
			sql.append(" and A.comp_type = :compType");
			param.put("compType", stdCompinfo.getCompType());
		}
		//判断企业id
		if(StringUtils.isNotBlank(stdCompinfo.getCompId())){
			sql.append(" and A.comp_id not in (:compIds) ");
			List<String> list = new ArrayList<String>();
			String[] strId = stdCompinfo.getCompId().split(",");
			for(int i=0;i<strId.length;i++){
				list.add(strId[i]);
			}
			param.put("compIds", list);
		}
		if (null != stdCompinfo.getAreaId()
				&& !"".equals(stdCompinfo.getAreaId())) {
			sql.append(" and B.area_id = :areaId");
			param.put("areaId", stdCompinfo.getAreaId());
		}
		if (null != stdCompinfo.getCompName()
				&& !"".equals(stdCompinfo.getCompName())) {
			sql.append(" AND (A.comp_name  LIKE :compName OR A.comp_spel_code LIKE :compName ) ");
			param.put("compName", "%" + stdCompinfo.getCompName().trim() + "%");
		}
		if (null != stdCompinfo.getCompCode()
				&& !"".equals(stdCompinfo.getCompCode())) {
			sql.append(" and A.comp_code = :compCode");
			param.put("compCode", stdCompinfo.getCompCode().trim());
		}
		if (null != stdCompinfo.getCompRegId()
				&& !"".equals(stdCompinfo.getCompRegId())) {
			sql.append(" and A.comp_reg_id = :compRegId");
			param.put("compRegId", stdCompinfo.getCompRegId());
		}
		if (null != stdCompinfo.getStatus()&& !"".equals(stdCompinfo.getStatus())) {
			sql.append(" and A.status = :status");
			param.put("status", stdCompinfo.getStatus());
		}
		sql.append(" order by A.comp_code desc ");
		return hibernateSqlUtil.getSqlPageMapList(sql.toString(), param, page);
	}

	

	


	
	
	/**
	 * 启用停用
	 */
	@Override
	public int batchStarts(StdCompinfo stdCompinfo) {
		Session session = getSession();
		StringBuffer sql = new StringBuffer();
		sql.append(" update std_compinfo set ")
			.append(" status=:status,upd_datetime=:updDatetime,upd_user=:updUser ")
			.append(" where comp_id= :compId and status <> :status ");
		Query update = session.createSQLQuery(sql.toString());
		update.setLong("status", stdCompinfo.getStatus());
		update.setString("updUser", stdCompinfo.getUpdUser());
		update.setTimestamp("updDatetime", new Date());
		update.setString("compId", stdCompinfo.getCompId());
		int count = update.executeUpdate();
		session.flush();
		if(count>0){
			writeLog(stdCompinfo);	
		}
		return count;
	}
	
	/**
	 * 写日志
	 * @category 
	 * @Auther 徐国鹏
	 * @date 2015年9月21日 上午9:41:22
	 * @param stdCompinfo
	 * @return void
	 */
	@Override
	public void writeLog(StdCompinfo stdCompinfo){
		Session session = getSession();
		String uuid = UUID.randomUUID().toString();
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into std_compinfo_log(log_id,comp_id,comp_code,comp_name,comp_spel_code,comp_name_eng,comp_short_name, ")
			.append(" comp_short_spel_code,comp_type,comp_reg_id,area_id,org_code,comp_group_id,comp_phone,comp_address,comp_classify,  ")
			.append(" status,upd_datetime,upd_user,history_code,merge_state,detail) select ")
		    .append(" :uuid,t.comp_id,t.comp_code,t.comp_name,t.comp_spel_code,t.comp_name_eng,t.comp_short_name,t.comp_short_spel_code,t.comp_type,t.comp_reg_id,t.area_id,t.org_code,t.comp_group_id,t.comp_phone,t.comp_address,t.comp_classify,t.status,t.upd_datetime,t.upd_user,t.history_code,t.merge_state,:detail from std_compinfo t where t.comp_id= :compId ");
		Query query=session.createSQLQuery(sql.toString());
		query.setString("uuid", uuid);
		query.setString("compId",stdCompinfo.getCompId());
		query.setString("detail", getDetail(stdCompinfo.getCompId()));
		query.executeUpdate();
		session.flush();
		
		StringBuffer sql2 = new StringBuffer()
		.append("insert into std_compinfo_detail_log select :uuid,t.* from std_compinfo_detail t where t.comp_id = :compId ");
		Query query2 =session.createSQLQuery(sql2.toString());
		query2.setString("uuid", uuid);
		query2.setString("compId", stdCompinfo.getCompId());
		query2.executeUpdate();
		session.flush();
		
	}
	

	/**
	 * 企业库 根据id查询数据
	 * 
	 * @param Id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<StdCompinfo> queryStdCompinfoById(String Id) {
		StringBuffer hql = new StringBuffer();
		hql.append(" select t.* from std_compinfo t where t.comp_id = :Id ");
		Query query = getSession().createSQLQuery(hql.toString()).addEntity("t",StdCompinfo.class);
		query.setParameter("Id", Id);
		return query.list();
	}
	
	@SuppressWarnings("unchecked")
	public StdCompinfo getCompInfoByCode(String compCode) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(StdCompinfo.class);
		criteria.add(Restrictions.eq("compCode", compCode));
		List<StdCompinfo> list = criteria.list();
		if (!list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}
	
	public DicCompType getDicCompRegId(String compRegid){
		if(compRegid!=null){
			DicCompType data = (DicCompType) getSession().get(DicCompType.class, compRegid);
			return data;
		}
		return null;
    }


	/**
	 * 企业库 维护记录查询所有及条件查询
	 * 
	 * @param stdCompinfoLog
	 * @return
	 */
	@SuppressWarnings({ "unchecked" })
	@Override
	public List<StdCompinfoLog> queryStdCompinfoLogByName(Pagination page,
			StdCompinfoLog stdCompinfoLog) {
		try {
			String compId = stdCompinfoLog.getCompId();
			String date1 = stdCompinfoLog.getCompCode();
			String date2 = stdCompinfoLog.getCompName();
			Short status = stdCompinfoLog.getStatus();
			StringBuffer hql = new StringBuffer();
			hql.append(" from StdCompinfoLog stdl where stdl.compId = :compId ");
			if (status != null) {
				hql.append(" and stdl.status = :status ");
			}
			if (StringUtils.isNotEmpty(date1)) {
				hql.append(" and stdl.updDatetime >= :date1");
			}
			if (StringUtils.isNotEmpty(date2)) {
				hql.append(" and stdl.updDatetime <= :date2 ");
			}

			Query query = getSession().createQuery(hql.toString());

			query.setParameter("compId", compId);

			if (status != null) {
				query.setParameter("status", status);
			}
			if (StringUtils.isNotEmpty(date1)) {
				query.setParameter("date1",
						Timestamp.valueOf(date1 + " 00:00:00"));
			}
			if (StringUtils.isNotEmpty(date2)) {
				query.setParameter("date2",
						Timestamp.valueOf(date2 + " 23:59:59"));
			}
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getMaxResults());
			return query.list();
		} catch (Exception e) {
			log.info("查询维护记录异常-->", e);
			return new ArrayList<StdCompinfoLog>();
		}
	}

	/**
	 * 企业库 信息详情对比数据
	 * 
	 * @param page
	 * @param stdCompinfoLog
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<Map<String,Object>> queryStdCompinfoLogById(Pagination page,StdCompinfoLog stdCompinfoLog) {
		String compId = stdCompinfoLog.getCompId();
		Timestamp updDatetime = stdCompinfoLog.getUpdDatetime();
		
		StringBuffer hql = new StringBuffer()
		.append("select a.comp_code,a.comp_name,a.comp_spel_code,a.comp_name_eng,a.comp_short_name,a.comp_short_spel_code,a.comp_type,")
		.append("c.area_name,d.comp_reg_name,a.org_code,e.comp_group_name,a.comp_phone,a.comp_address,a.comp_classify,a.status,b.reg_cap,")
		.append("b.biz_scope,b.legal_rep_name,b.legal_rep_idnum,b.legal_rep_telephone,b.legal_rep_handphone,b.contact_name,")
		.append("b.contact_idnum,b.contact_pos,b.contact_telephone,b.contact_handphone,b.contact_email,b.contact_qq,b.biz_lice_no,")
		.append("DATE_FORMAT(b.biz_lice_start_date,'%Y-%m-%d %H:%i:%S') biz_lice_start_date,DATE_FORMAT(b.biz_lice_end_date,'%Y-%m-%d %H:%i:%S') biz_lice_end_date,b.tax_code,")
		.append("b.indus_code,DATE_FORMAT(b.indus_code_start_date,'%Y-%m-%d %H:%i:%S') indus_code_start_date,DATE_FORMAT(b.indus_code_end_date,'%Y-%m-%d %H:%i:%S') indus_code_end_date,")
		.append("b.legal_rep_cert_code,DATE_FORMAT(b.legal_rep_start_date,'%Y-%m-%d %H:%i:%S') legal_rep_start_date,DATE_FORMAT(b.legal_rep_end_date,'%Y-%m-%d %H:%i:%S') legal_rep_end_date, ")
		.append("f.name,DATE_FORMAT(a.upd_datetime,'%Y-%m-%d %H:%i:%S') upd_datetime");
		
		hql.append(" from std_compinfo_log a ");
		hql.append(" JOIN std_compinfo_detail_log b on b.log_id=a.log_id ");
		hql.append(" LEFT JOIN sys_user f on f.id=a.upd_user ");
		hql.append(" left join dic_comptype d on d.comp_reg_id=a.comp_reg_id");
		hql.append(" left join std_compgroup e on e.comp_group_id=a.comp_group_id ");
		hql.append(" left join dic_area c on c.area_id = a.area_id   ");
		hql.append(" where a.comp_id = :compId and a.upd_datetime <= :updDatetime ");
		hql.append(" order by a.upd_datetime desc limit 2 ");
		Query query = this.getSession().createSQLQuery(hql.toString());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		query.setString("compId", compId);
		query.setTimestamp("updDatetime", updDatetime);
		
		return query.list();
		
	}

	/**
	 * @category 根据企业id 查询企业详情
	 * @author 韩守松
	 * @date   2015年8月21日
	 * @param  @param compId
	 * @param  @return
	 */
	public StdCompinfo queryStdCompInfoByCompId(String compId) {
		StringBuffer hql = new StringBuffer();
		hql.append("from StdCompinfo where comp_id = :compId ");
		Query query = this.getSession().createQuery(hql.toString());
		query.setString("compId", compId);
		return (StdCompinfo)query.uniqueResult();
	}
	
	/**
	 * @category 根据企业compCode 查询企业详情
	 * @author 韩守松
	 * @date   2015年8月21日
	 * @param  @param compCode
	 * @param  @return
	 */
	public StdCompinfo queryStdCompInfoByCompCode(String compCode) {
		StringBuffer hql = new StringBuffer();
		hql.append("from StdCompinfo where comp_code = :compCode ");
		Query query = this.getSession().createQuery(hql.toString());
		query.setString("compCode", compCode);
		return (StdCompinfo)query.uniqueResult();
	}
	/**
	 * 企业库 根据企业id 及状态 查询企业数据
	 * 
	 * @param page
	 * @param stdCompinfo
	 * @return
	 */
	@Override
	public Pagination queryStdCompinfoById(Pagination page,
			StdCompinfo stdCompinfo) {
		try {
			String compId = stdCompinfo.getCompId();
			Short compType = stdCompinfo.getCompType();
			String areaId = stdCompinfo.getAreaId();
			String compRegId = stdCompinfo.getCompRegId();
			String compCode = stdCompinfo.getCompCode();
			String compName = stdCompinfo.getCompName();
			//String compSpelCode = stdCompinfo.getCompSpelCode();
			StringBuffer hqlCount = new StringBuffer();
			StringBuffer hql = new StringBuffer();
			hqlCount.append(" select count(*) ");
			hql.append("from StdCompinfo std where std.compId != :compId and std.status = 1 ");
			if (compType != null) {
				hql.append(" and std.compType = :compType ");
			}

			if (StringUtils.isNotEmpty(areaId)) {
				hql.append(" and std.areaId = :areaId ");
			}
			if (StringUtils.isNotEmpty(compRegId)) {
				hql.append(" and std.compRegId = :compRegId");
			}

			if (StringUtils.isNotEmpty(compCode)) {
				hql.append(" and std.compCode  like :compCode");
			}
			if (StringUtils.isNotEmpty(compName)) {
				hql.append(" and (std.compName  like :compName or std.compSpelCode like :compName )");
			}

			hqlCount.append( hql.toString());
			Query countQuery = getSession().createQuery(hqlCount.toString());
			
			Query query = getSession().createQuery(hql.toString());
			countQuery.setParameter("compId", compId);
			query.setParameter("compId", compId);
			if (compType != null) {
				countQuery.setParameter("compType", compType);
				query.setParameter("compType", compType);
			}

			if (StringUtils.isNotEmpty(areaId)) {
				countQuery.setParameter("areaId", areaId);
				query.setParameter("areaId", areaId);
			}
			if (StringUtils.isNotEmpty(compRegId)) {
				countQuery.setParameter("compRegId", compRegId);
				query.setParameter("compRegId", compRegId);
			}

			if (StringUtils.isNotEmpty(compCode)) {
				countQuery.setParameter("compCode", "%" + compCode.trim() + "%");
				query.setParameter("compCode", "%" + compCode.trim() + "%");
			}
			if (StringUtils.isNotEmpty(compName)) {
				countQuery.setParameter("compName", "%" + compName.trim() + "%");
				query.setParameter("compName", "%" + compName.trim() + "%");
			}
			Long result = Long.valueOf(countQuery.uniqueResult().toString());
			page.setRecords(result);
			query.setFirstResult(page.getFirstResult());
			query.setMaxResults(page.getMaxResults());
			page.setRows(query.list());
			return page;
		} catch (Exception e) {
			log.info("企业库数据查询异常-->" + e);
			return page;
		}
	}

	/**
	 * 企业库 根据企业id查询状态为1的数据
	 * 
	 * @param Id
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<StdCompinfo> queryStdCompinfoByIdForMerge(String Id) {
		StringBuffer hql = new StringBuffer();
		hql.append("from StdCompinfo where comp_id = ? and status = 1 ");
		Query query = this.getSession().createQuery(hql.toString());
		query.setParameter(0, Id);
		return query.list();
	}

	public void LogSave(StdCompinfo stdCompinfo) {
		// 记录企业库日志
		StdCompinfoLog stdCompinfoLog = new StdCompinfoLog();
		stdCompinfoLog.setCompId(stdCompinfo.getCompId());
		stdCompinfoLog.setCompCode(stdCompinfo.getCompCode());
		stdCompinfoLog.setCompName(stdCompinfo.getCompName());
		stdCompinfoLog.setCompSpelCode(stdCompinfo.getCompSpelCode());
		stdCompinfoLog.setCompNameEng(stdCompinfo.getCompNameEng());
		stdCompinfoLog.setCompShortName(stdCompinfo.getCompShortName());
		stdCompinfoLog.setCompShortSpelCode(stdCompinfo.getCompShortSpelCode());
		stdCompinfoLog.setCompType(stdCompinfo.getCompType());
		stdCompinfoLog.setDicCompType(stdCompinfo.getDicCompType());
		stdCompinfoLog.setCompRegId(stdCompinfo.getCompRegId());// 注册类型id
		stdCompinfoLog.setDicArea(stdCompinfo.getDicArea());
		stdCompinfoLog.setAreaId(stdCompinfo.getAreaId());// 区域id
		stdCompinfoLog.setOrgCode(stdCompinfo.getOrgCode());

		stdCompinfoLog.setStdCompgroup(stdCompinfo.getStdCompgroup());
		stdCompinfoLog.setCompGroupId(stdCompinfo.getCompGroupId());// 集团id
		stdCompinfoLog.setCompPhone(stdCompinfo.getCompPhone());
		stdCompinfoLog.setCompAddress(stdCompinfo.getCompAddress());
		stdCompinfoLog.setCompClassify(stdCompinfo.getCompClassify());
		stdCompinfoLog.setStatus(stdCompinfo.getStatus());
		stdCompinfoLog.setUpdUser(stdCompinfo.getUpdUser());
		stdCompinfoLog.setUpdDatetime(stdCompinfo.getUpdDatetime());
		stdCompinfoLog.setHistoryCode(stdCompinfo.getHistoryCode());
		stdCompinfoLog.setMergeState(stdCompinfo.getMergeState());
		stdCompinfoLog.setDetail(getDetail(stdCompinfo.getCompId()));
		this.getSession().save(stdCompinfoLog);
		this.getSession().flush();
		if(null != stdCompinfo.getStdCompinfoDetail()){
			// 记录企业库详细信息日志
			StdCompinfoDetailLog stdCompinfoDetailLog = new StdCompinfoDetailLog();
			stdCompinfoDetailLog.setLogId(stdCompinfoLog.getLogId());
			stdCompinfoDetailLog.setCompId(stdCompinfo.getStdCompinfoDetail()
					.getCompId());
			stdCompinfoDetailLog.setRegCap(stdCompinfo.getStdCompinfoDetail()
					.getRegCap());// 企业注册资本
			stdCompinfoDetailLog.setCompProfile(stdCompinfo.getStdCompinfoDetail()
					.getCompProfile());// 企业简称
			stdCompinfoDetailLog.setBizScope(stdCompinfo.getStdCompinfoDetail()
					.getBizScope());
			stdCompinfoDetailLog.setLegalRepName(stdCompinfo.getStdCompinfoDetail()
					.getLegalRepName());
			stdCompinfoDetailLog.setLegalRepIdnum(stdCompinfo
					.getStdCompinfoDetail().getLegalRepIdnum());
			stdCompinfoDetailLog.setLegalRepTelephone(stdCompinfo
					.getStdCompinfoDetail().getLegalRepTelephone());
			stdCompinfoDetailLog.setLegalRepHandphone(stdCompinfo
					.getStdCompinfoDetail().getLegalRepHandphone());
			stdCompinfoDetailLog.setContactName(stdCompinfo.getStdCompinfoDetail()
					.getContactName());
			stdCompinfoDetailLog.setContactIdnum(stdCompinfo.getStdCompinfoDetail()
					.getContactIdnum());
			stdCompinfoDetailLog.setContactPos(stdCompinfo.getStdCompinfoDetail()
					.getContactPos());
			stdCompinfoDetailLog.setContactTelephone(stdCompinfo
					.getStdCompinfoDetail().getContactTelephone());
			stdCompinfoDetailLog.setContactHandphone(stdCompinfo
					.getStdCompinfoDetail().getContactHandphone());
			stdCompinfoDetailLog.setContactEmail(stdCompinfo.getStdCompinfoDetail()
					.getContactEmail());
			stdCompinfoDetailLog.setContactQq(stdCompinfo.getStdCompinfoDetail()
					.getContactQq());
			stdCompinfoDetailLog.setBizLiceNo(stdCompinfo.getStdCompinfoDetail()
					.getBizLiceNo());
			stdCompinfoDetailLog.setBizLiceStartDate(stdCompinfo
					.getStdCompinfoDetail().getBizLiceStartDate());
			stdCompinfoDetailLog.setBizLiceEndDate(stdCompinfo
					.getStdCompinfoDetail().getBizLiceEndDate());
			stdCompinfoDetailLog.setTaxCode(stdCompinfo.getStdCompinfoDetail()
					.getTaxCode());
			stdCompinfoDetailLog.setIndusCode(stdCompinfo.getStdCompinfoDetail()
					.getIndusCode());
			stdCompinfoDetailLog.setIndusCodeStartDate(stdCompinfo
					.getStdCompinfoDetail().getIndusCodeStartDate());
			stdCompinfoDetailLog.setIndusCodeEndDate(stdCompinfo
					.getStdCompinfoDetail().getIndusCodeEndDate());
			stdCompinfoDetailLog.setLegalRepCertCode(stdCompinfo
					.getStdCompinfoDetail().getLegalRepCertCode());
			stdCompinfoDetailLog.setLegalRepStartDate(stdCompinfo
					.getStdCompinfoDetail().getLegalRepStartDate());
			stdCompinfoDetailLog.setLegalRepEndDate(stdCompinfo.getStdCompinfoDetail().getLegalRepEndDate());
			stdCompinfoDetailLog.setUpdDatetime(stdCompinfo.getUpdDatetime());
			stdCompinfoDetailLog.setUpdUser(stdCompinfo.getUpdUser());

			this.getSession().save(stdCompinfoDetailLog);
			this.getSession().flush();
		}
	}
	
	/**
	 * 获取日志表中detail字段的值
	 * @category 
	 * @Auther wangbing
	 * @date 2015年9月21日 上午9:41:22
	 * @param stdCompinfo
	 * @return void
	 */
	private String getDetail(String compId){
		StringBuffer sb = new StringBuffer()
		.append("select a.comp_code,a.comp_name,a.comp_spel_code,a.comp_name_eng,a.comp_short_name,a.comp_short_spel_code,a.comp_type,")
		.append("c.area_name,d.comp_reg_name,a.org_code,e.comp_group_name,a.comp_phone,a.comp_address,a.comp_classify,a.status,b.reg_cap,")
		.append("b.biz_scope,b.legal_rep_name,b.legal_rep_idnum,b.legal_rep_telephone,b.legal_rep_handphone,b.contact_name,")
		.append("b.contact_idnum,b.contact_pos,b.contact_telephone,b.contact_handphone,b.contact_email,b.contact_qq,b.biz_lice_no,")
		.append("DATE_FORMAT(b.biz_lice_start_date,'%Y-%m-%d'),DATE_FORMAT(b.biz_lice_end_date,'%Y-%m-%d'),b.tax_code,")
		.append("b.indus_code,DATE_FORMAT(b.indus_code_start_date,'%Y-%m-%d'),DATE_FORMAT(b.indus_code_end_date,'%Y-%m-%d'),")
		.append("b.legal_rep_cert_code,DATE_FORMAT(b.legal_rep_start_date,'%Y-%m-%d'),DATE_FORMAT(b.legal_rep_end_date,'%Y-%m-%d') ");
		
		StringBuffer leftJoin = new StringBuffer()
		.append(" left join dic_area c on c.area_id = a.area_id ")
		.append(" left join dic_compType d on d.comp_reg_id = a.comp_reg_id ")
		.append(" left join std_compgroup e on e.comp_group_id = a.comp_group_id ");
		
		StringBuffer sql = new StringBuffer()
		.append(sb.toString())
		.append(" from std_compinfo a join std_compinfo_detail b on b.comp_id = a.comp_id  ")
		.append(leftJoin.toString())
		.append(" where a.comp_id = :compId ")
		.append(" union all ")
		.append(" select t.* from ( ")
		.append(sb.toString())
		.append(" from std_compinfo_log a join std_compinfo_detail_log b on b.log_id = a.log_id ")
		.append(leftJoin.toString())
		.append(" where a.comp_id = :compId order by a.upd_datetime desc limit 1 ) t ");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("compId", compId);
		List<?> list = hibernateSqlUtil.getSqlList(sql.toString(), params);
		
		StringBuffer detail = new StringBuffer();
		String[] colName ={"企业编码","企业名称","企业名称拼音码","企业英文名称","企业简称","简称拼音码","企业类型","地区","企业注册类型","组织机构代码","所属集团","机构电话","机构地址","企业分类","状态","注册资本","营业范围","法人姓名","法人身份证号","法人电话","法人手机","联系人姓名","联系人身份证号","联系人职务","联系人电话","联系人手机","联系人邮箱","联系人QQ","营业执照编号","营业执照有效期始","营业执照有效期止","税务登记证号","经营许可证编号","经营许可证有效期始","经营许可证有效期止","企业法人营业执照号","企业法人营业执照号有效期始","企业法人营业执照号有效期止"};
		if(list.size()==1){
			Object[] obj =(Object[]) list.get(0);
			obj[6] = obj[6]==null?"":"1".equals(obj[6].toString())?"生产企业":"配送企业";
			obj[13] = obj[13]==null?"":"0".equals(obj[13].toString())?"默认":"1".equals(obj[13].toString())?"药品":"2".equals(obj[13].toString())?"耗材":"3".equals(obj[13].toString())?"药品耗材":"";
			obj[14] = obj[14]==null?"":"1".equals(obj[14].toString())?"启用":"2".equals(obj[14].toString())?"停用":"合并";
			for(int i = 0;i<obj.length;i++){
				detail.append(";").append(colName[i]).append(":").append(obj[i]==null?"":obj[i].toString());
			}
			detail.delete(0, 1);
		}else{
			Object[] obj1 =(Object[]) list.get(0);//修改后
			Object[] obj2 =(Object[]) list.get(1);//修改前
			obj1[6] = obj1[6]==null?"":"1".equals(obj1[6].toString())?"生产企业":"配送企业";
			obj2[6] = obj2[6]==null?"":"1".equals(obj2[6].toString())?"生产企业":"配送企业";
			obj1[13] = obj1[13]==null?"":"0".equals(obj1[13].toString())?"默认":"1".equals(obj1[13].toString())?"药品":"2".equals(obj1[13].toString())?"耗材":"3".equals(obj1[13].toString())?"药品耗材":"";
			obj2[13] = obj2[13]==null?"":"0".equals(obj2[13].toString())?"默认":"1".equals(obj2[13].toString())?"药品":"2".equals(obj2[13].toString())?"耗材":"3".equals(obj2[13].toString())?"药品耗材":"";
			obj1[14] = obj1[14]==null?"":"1".equals(obj1[14].toString())?"启用":"2".equals(obj1[14].toString())?"停用":"合并";
			obj2[14] = obj2[14]==null?"":"1".equals(obj2[14].toString())?"启用":"2".equals(obj2[14].toString())?"停用":"合并";
			for(int i = 0;i<obj1.length;i++){
				if(!(obj1[i]==null?"":obj1[i].toString()).equals(obj2[i]==null?"":obj2[i].toString())){
					detail.append(";").append(colName[i]).append(":").append(obj2[i]==null?"":obj2[i].toString()).append(",").append(obj1[i]==null?"":obj1[i].toString());
				}
				
			}
			detail.delete(0, 1);
		}
		return detail.toString();
	}
	
	/**
	 * 根据条件获取不分页数据
	 * @param page
	 * @return page
	 */
	@Override
	public Pagination getStdCompinfoNoPage(Pagination page){
		Map<String,String> params = new HashMap<String, String>();
		String compCode = page.getConditions().get("compCode");
		String compName = page.getConditions().get("compName");
		String compType = page.getConditions().get("compType");
		String compRegId = page.getConditions().get("compRegId");
		String areaId = page.getConditions().get("areaId");
		String status = page.getConditions().get("status");
		StringBuffer sql = new StringBuffer()
		.append("	SELECT ")
		.append("	a.comp_code compCode,a.comp_name compName,a.comp_spel_code compSpelCode,a.comp_name_eng compNameEng,")
		.append("	a.comp_short_name compShortName,a.comp_short_spel_code compShortSpelCode,")
		.append("	CASE a.comp_type WHEN 1 THEN '生产企业' WHEN '2' THEN '配送企业' ELSE '' END compType,")
		.append("	c.area_name areaName ,d.comp_reg_name compRegName,")
		.append("	a.org_code orgCode,e.comp_group_name compGroupName,a.comp_phone compPhone,a.comp_address compAddress,")
		.append("	CASE a.comp_classify WHEN 3 THEN '药品耗材' WHEN 2 THEN '耗材' WHEN 1 THEN '药品' ELSE '默认' END compClassify,")
		.append("	CASE a.status WHEN 3 THEN '合并' WHEN 2 THEN '停用' ELSE '启用' END status,")
		.append("	b.reg_cap regCap,b.biz_scope bizScope,")
		.append("	b.legal_rep_name legalRepName,b.legal_rep_idnum legalRepIdnum,")
		.append("	b.legal_rep_telephone legalRepTelephone,b.legal_rep_handphone legalRepHandphone,")
		.append("	b.contact_name contactName,b.contact_idnum contactIdnum,b.contact_pos contactPos,")
		.append("	b.contact_telephone contactTelephone,b.contact_handphone contactHandphone,")
		.append("	b.contact_email contactEmail,b.contact_qq contactQq,b.biz_lice_no bizLiceNo,")
		.append("	DATE_FORMAT(b.biz_lice_start_date,'%Y-%m-%d') bizLiceStartDate,")
		.append("	DATE_FORMAT(b.biz_lice_end_date,'%Y-%m-%d') bizLiceEndDate,")
		.append("	b.tax_code taxCode,b.indus_code indusCode,")
		.append("	DATE_FORMAT(b.indus_code_start_date,'%Y-%m-%d') indusCodeStartDate,")
		.append("	DATE_FORMAT(b.indus_code_end_date,'%Y-%m-%d') indusCodeEndDate,")
		.append("	b.legal_rep_cert_code legalRepCertCode,")
		.append("	DATE_FORMAT(b.legal_rep_start_date,'%Y-%m-%d') legalRepStartDate,")
		.append("	DATE_FORMAT(b.legal_rep_end_date,'%Y-%m-%d') legalRepEndDate")
		.append("	FROM std_compinfo a JOIN std_compinfo_detail b ON b.comp_id = a.comp_id")
		.append("	LEFT JOIN dic_area c ON c.area_id = a.area_id ")
		.append("	LEFT JOIN dic_comptype d ON d.comp_reg_id = a.comp_reg_id ")
		.append("	LEFT JOIN std_compgroup e ON e.comp_group_id = a.comp_group_id ")
		.append("	WHERE 1 = 1");
		if(StringUtils.isNotBlank(compCode)){
			sql.append(" and a.comp_code = :compCode ");
			params.put("compCode", compCode);
		}
		if(StringUtils.isNotBlank(compName)){
			sql.append(" and a.comp_name like :compName ");
			params.put("compName", "%"+compName+"%");
		}
		if(StringUtils.isNotBlank(compType)){
			sql.append(" and a.comp_type = :compType ");
			params.put("compType", compType);
		}
		if(StringUtils.isNotBlank(compRegId)){
			sql.append(" and a.comp_reg_id = :compRegId ");
			params.put("compRegId", compRegId);
		}
		if(StringUtils.isNotBlank(areaId)){
			sql.append(" and a.area_id like :areaId ");
			params.put("areaId", areaId+"%");
		}
		if(StringUtils.isNotBlank(status)){
			sql.append(" and a.status = :status ");
			params.put("status", status);
		}
		sql.append("	ORDER BY a.comp_name ");
		page.setRows(hibernateSqlUtil.getSqlMapList(sql.toString(), params));
		return page;
	}

	@Override
	public Pagination queryStdCompCount(Pagination page) {
		StringBuffer sql = new StringBuffer();
		sql.append("SELECT count(*) FROM std_compinfo A  where  A.status = 1 and A.comp_type = 2");
		Query countQuery = getSession().createSQLQuery(sql.toString());
		BigInteger records = (BigInteger) countQuery.uniqueResult();
		page.setRows((records.longValue()));
		return page;
	}
	@SuppressWarnings("unchecked")
	public List<Map<String, Object>> getCompByName(String compName){
		Session session = sessionFactory.openSession();
		String sql = "select * from std_compinfo where comp_name = :compName";
		Query query = session.createSQLQuery(sql);
		query.setString("compName", compName);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<Map<String, Object>> list = query.list();
		session.clear();
		session.close();
		return list;
	}
	
	/**
	 * @category 根据企业名称或简拼搜索企业
	 * @date 2015年11月19日
	 * @param compName
	 * @return
	 */
	public Pagination searchCompByName(Pagination page) {
		StringBuilder sb = new StringBuilder();
		sb.append(" SELECT a.comp_spel_code py, a.comp_name name, a.comp_code code FROM std_compinfo a  ");
		sb.append(" WHERE a.comp_name LIKE :compName || a.comp_spel_code LIKE :compName ");
		
		Session session = getSession();
		SQLQuery query = session.createSQLQuery(sb.toString());
		
		String compName = page.getConditions().get("compName");
		query.setString("compName", "%" + compName + "%");
		query.setFirstResult(0);
		query.setMaxResults(10);
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}
	@SuppressWarnings("unchecked")
	public Map<String, Object> getCompinfoByCode(String compCode){
		String sql = "select * from std_compinfo t where t.comp_code = :compCode";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("compCode", compCode);
		List<Map<String, Object>> list = (List<Map<String, Object>>) hibernateSqlUtil.getSqlMapList(sql, params);
		if (null != list && list.size() > 0){
			return list.get(0);
		}
		return null;
	}
	public Pagination getCompList(Pagination page){
		StringBuffer sql = new StringBuffer()
		.append("select * from std_compinfo t where t.status = 1");
		Map<String, Object> params = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(page.getConditions().get("compName"))){
			sql.append(" and (t.comp_name like :compName or t.comp_spel_code like :compSelCode)");
			params.put("compName", "%" + page.getConditions().get("compName").trim() + "%");
			params.put("compSelCode", "%" + page.getConditions().get("compName").trim().toUpperCase() + "%");
		}
		if (StringUtils.isNotBlank(page.getConditions().get("type"))){
			sql.append(" and t.comp_type = :compType");
			params.put("compType", page.getConditions().get("type").trim());
		}
		return hibernateSqlUtil.getSqlPageMapList(sql.toString(), params, page);
	}
	
	/**
	 * @category 根据企业类型获取此类型下的企业数据
	 * @author 韩守松
	 * @date   2016年1月13日
	 * @param  @param compType
	 * @param  @return
	 */
	public Pagination getCompData(Integer compType,Pagination page){
		StringBuffer hql = new StringBuffer();
		hql.append(" select comp_id prodCompId,status prodCompStatus,comp_code compCode,comp_name compName,comp_type compType from std_compinfo where  comp_type = :compType and status = :status ");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("compType", compType);
		params.put("status", Status.enabled.getKey());
		
		// 查询条件
		StdProdDrugInfoForm form = (StdProdDrugInfoForm) page.getForm();
		if (form != null) {
			// 企业编码
			String compCode = form.getCompCode();
			if (StringUtils.isNotBlank(compCode)) {
				hql.append(" AND comp_code = :compCode ");
				params.put("compCode", compCode.trim());
			}

			// 企业名称
			String compName = form.getCompName();
			if (StringUtils.isNotBlank(compName)) {
				hql.append(" AND (comp_name LIKE :compName OR comp_spel_code LIKE :compName) ");
				params.put("compName", "%" + compName.trim()+ "%");
			}
		
		}

		return hibernateSqlUtil.getSqlPageMapList(hql.toString(), params, page);
	}
}














